from readTMM import JiraData
from datetime import datetime
from datetime import date
from datetime import timedelta
import calendar
import xlrd
import xlwt

def printCal(user, range):
    cal_task = getCalendarData(user, range)
    # print(cal_task)
    # cal_task = {"2016-6-3":[("123","456",("12","34"))],"2016-6-9":[("1234","4567",("102","304")),("1234","4567",("102","304"))]}
    title = ""
    if 0 == range:
        title = "本月工作日历"
    elif 1 == range:
        title = "本季度工作日历"
    elif 2 == range:
        title = "本年度工作日历"
    write_to_xls(user, title, cal_task)

def getCalendarData(user, range):
    """user为要打印的用户名，range=0 打印当月， range=1 打印当季度， range=2 打印当年"""
    stimerange = (getTimeRange(range)[0],getTimeRange(range)[2])
    ctimerange = (getTimeRange(range)[0],getTimeRange(range)[1])
    tasks = JiraData().getInfoByUser(user,stimerange)
    alltaskinfo = []
    for task in tasks:
        summary = task.fields.summary
        storypoint = task.fields.customfield_10002
        createdate = task.fields.created[0:10]
        startdate = task.fields.customfield_10200
        duedate = task.fields.duedate
        taskdate = dealTaskDate(createdate, startdate, duedate, storypoint)
        parent_summary = searchTPRTMMMap(task)
        taskinfo = (parent_summary, summary, taskdate)
        alltaskinfo.append(taskinfo)
    currentYear = datetime.now().year
    currentMonth = datetime.now().month
    if ctimerange[0].__contains__("-"):
        cal_begin = datetime.strptime(ctimerange[0],"%Y-%m-%d")
        cal_begin = date(cal_begin.year, cal_begin.month, cal_begin.day)
        cal_end = datetime.strptime(ctimerange[1],"%Y-%m-%d")
        cal_end = date(cal_end.year, cal_end.month, cal_end.day)
    elif ctimerange[0].__contains__("Month"):
        cal_begin = date(currentYear, currentMonth, 1)
        cal_end = date(currentYear, currentMonth, calendar.monthrange(currentYear, currentMonth)[1])
    elif ctimerange[0].__contains__("Year"):
        cal_begin = date(currentYear, 1, 1)
        cal_end = date(currentYear, 12, calendar.monthrange(currentYear, 12)[1])
    cal_task = {}
    workdate = cal_begin
    while workdate >= cal_begin and workdate <= cal_end:
        date_items = []
        for p_task in alltaskinfo:
            if workdate >= p_task[2][0] and workdate <= p_task[2][1]:
                date_items.append(p_task)
        cal_task.setdefault(workdate,date_items)
        workdate = workdate + timedelta(1)
    return cal_task

def write_to_xls(user, title, cal_task):
    style_date = xlwt.XFStyle()  # 初始化样式
    style_des = xlwt.XFStyle()
    font_date = xlwt.Font()  # 为样式创建字体
    font_date.name = u"微软雅黑"  # 'Times New Roman'
    font_date.bold = "bold"
    font_date.colour_index = 20

    borders= xlwt.Borders()
    borders.left= 6
    borders.right= 6
    borders.top= 6
    borders.bottom= 6

    style_date.font = font_date
    style_date.borders = borders

    f = xlwt.Workbook()  # 创建工作簿

    sheet1 = f.add_sheet(user, cell_overwrite_ok=True)  # 创建sheet
    sheet1.write(0, 2, datetime.today().year, style_date)
    sheet1.write(0, 3, title, style_date)
    week_title = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
    for i in range (0,len(week_title)):
        sheet1.write(1, i, week_title[i],style_date)

    row = 2
    max = row
    for daydata in cal_task:
        con_date = str(daydata)
        col = datetime.strptime(con_date,"%Y-%m-%d").weekday()
        date_row = row
        sheet1.write(date_row, col, con_date, style_date)
        date_row = date_row + 1
        date_info = cal_task.get(daydata)
        for task in date_info:
            con_project = task[0]
            sheet1.write(date_row, col, con_project)
            date_row = date_row + 1
            con_task = task[1]
            sheet1.write(date_row, col, con_task)
            date_row = date_row + 1
        if max < date_row:
            max = date_row
        if 6 == col:
            row = max



    # row0 = [u'业务', u'状态', u'北京', u'上海', u'广州', u'深圳', u'状态小计', u'合计']
    # column0 = [u'机票', u'船票', u'火车票', u'汽车票', u'其它']
    # status = [u'预订', u'出票', u'退票', u'业务小计']
    #
    # # 生成第一行
    # for i in range(0, len(row0)):
    #     sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True))
    #
    # # 生成第一列和最后一列(合并4行)
    # i, j = 1, 0
    # while i < 4 * len(column0) and j < len(column0):
    #     sheet1.write_merge(i, i + 3, 0, 0, column0[j], set_style('Arial', 220, True))  # 第一列
    #     sheet1.write_merge(i, i + 3, 7, 7)  # 最后一列"合计"
    #     i += 4
    #     j += 1
    #
    # sheet1.write_merge(21, 21, 0, 1, u'合计', set_style('Times New Roman', 220, True))
    #
    # # 生成第二列
    # i = 0
    # while i < 4 * len(column0):
    #     for j in range(0, len(status)):
    #         sheet1.write(j + i + 1, 1, status[j])
    #     i += 4
    #
    f.save(user + '-calendar.xls')  # 保存文件

def getTimeRange(range):
    """返回的三个值分别为jira月起始查询值，自然月结束查询值，延展至下月5号查询值"""
    timeRangeMap = {0: "Month", 1: "Season", 2: "Year"}
    timeRange = timeRangeMap.get(range, "Other")
    currentTime = datetime.now()
    currentMonth = currentTime.month
    currentYear = currentTime.year
    fromMonth = currentMonth
    dueMonth = currentMonth
    lastday = "-30"
    startDate = currentTime.date()
    endDate = currentTime.date()
    _endDate = currentTime.date()
    if timeRange == "Month":
        startDate = "startOfMonth()"
        endDate = "endOfMonth()"
        _endDate = str(currentYear) + "-" + str(dueMonth + 1) + "-05"
    elif timeRange == "Season":
        if currentMonth in (1, 2, 3):
            fromMonth = 1
            dueMonth = 3
            lastday = "-31"
        elif currentMonth in (4, 5, 6):
            fromMonth = 4
            dueMonth = 6
        elif currentMonth in (7, 8, 9):
            fromMonth = 7
            dueMonth = 9
        else:
            fromMonth = 10
            dueMonth = 12
            lastday = "-31"
        startDate = str(currentYear) + "-" + str(fromMonth) + "-01"
        endDate = str(currentYear) + "-" + str(dueMonth) + lastday
        if dueMonth != 12:
            _endDate = str(currentYear) + "-" + str(dueMonth + 1) + "-05"
        else:
            dueMonth = 0
            _endDate = str(currentYear + 1) + "-" + str(dueMonth + 1) + "-05"

    elif timeRange == "Year":
        startDate = "startOfYear()"
        endDate = "endOfYear()"
        dueMonth = 0
        _endDate = str(currentYear + 1) + "-" + str(dueMonth + 1) + "-05"
    else:
        print("时间范围参数错误，默认为您输出当前月份数据！")
        startDate = "startOfMonth()"
        endDate = "endOfMonth()"
        _endDate = str(currentYear) + "-" + str(dueMonth + 1) + "-05"
    return startDate,endDate,_endDate


def dealTaskDate(ocreatedate, ostartdate, oduedate, ostorypoint):
    ustartdate = ostartdate
    uduedate = oduedate
    if (str(ostartdate).startswith("20") is not True) or (str(oduedate).startswith("20") is not True):
        """startdate或duedate为空时，为所有story和task填充 startdate & duedate 信息"""
        if str(oduedate).startswith("20"):
            """如果duedate不为空，则startdate一定为空，用duedate - storypoint 得到 startdate"""
            if isinstance(ostorypoint, float):
                ustartdate = datetime.strptime(oduedate, "%Y-%m-%d")
                for i in range(1, round(ostorypoint)):
                    ustartdate = ustartdate - timedelta(1)
                    if ustartdate.weekday() is 6:
                        ustartdate = ustartdate - timedelta(2)
            else:
                """story points 为空时，默认为当天就能完成的事物，duedate 设为 startdate"""
                ustartdate = oduedate
            if isinstance(ustartdate, str) is True:
                ustartdate = datetime.strptime(ustartdate, "%Y-%m-%d")
        else:
            """duedate为空，如果startdate也为空，则先填充startdate信息，同时处理duedate"""
            if str(ostartdate).startswith("20") is not True:
                """并且startdate也为空，则用createdate填充startdate，并更新startdate"""
                ustartdate = ocreatedate
                if isinstance(ustartdate, str) is True:
                    ustartdate = datetime.strptime(ustartdate, "%Y-%m-%d")
            if isinstance(ostorypoint, float):
                uduedate = datetime.strptime(ocreatedate, "%Y-%m-%d")
                for i in range(1, round(ostorypoint)):
                    uduedate = uduedate + timedelta(1)
                    if uduedate.weekday() is 5:
                        uduedate = uduedate + timedelta(2)
            else:
                """如果story points 和 duedate 都为空，则默认为当天完成事件，用createdate 填充 startdate 和 duedate"""
                uduedate = ocreatedate
            if isinstance(uduedate, str) is True:
                uduedate = datetime.strptime(uduedate, "%Y-%m-%d")
    if isinstance(ustartdate, str) is True:
        ustartdate = datetime.strptime(ustartdate, "%Y-%m-%d")
    if isinstance(uduedate, str) is True:
        uduedate = datetime.strptime(uduedate, "%Y-%m-%d")
    ustartdate = date(ustartdate.year, ustartdate.month, ustartdate.day)
    uduedate = date(uduedate.year, uduedate.month, uduedate.day)
    return ustartdate, uduedate

def searchTPRTMMMap(issue):
    issuetype = ""
    issuekey = ""
    projectSummary = ""
    try:
        issuetype = str(issue.fields.issuetype)
        issuekey = str(issue.key)
    except:
        if str(issue).__contains__("not exist"):
            print(issue)
        else:
            print("参数类型错误，searchTPRTMMMap应传入一个jira Issue")
    else:
        pass
    if issuetype != "" and issuekey != "":
        map = getTPRMap()
        if issuetype.__contains__("Story"):
             for tpr_key in map.keys():
                 if projectSummary != "":
                     break
                 if issuekey in map.get(tpr_key).keys():
                     project = JiraData().getIssueByKey(str(tpr_key))
                     projectSummary = str(tpr_key) + ":" + project.fields.summary
        elif issuetype.__contains__("Task"):
            for tpr_key in map.keys():
                if projectSummary != "":
                    break
                for story_key in map.get(tpr_key).keys():
                    if issuekey in map.get(tpr_key).get(story_key):
                        project = JiraData().getIssueByKey(str(tpr_key))
                        projectSummary = str(tpr_key) + ":" + project.fields.summary
    return projectSummary

def getTPRMap():
    """TPRMap格式为{TPR1Key:{Story1Key:[task1key,task2key],Story2Key:[task1key,task2key]},TPR2Key:{},TPR3Key:{StoryKey:[]}}"""
    TPRMap = {}
    jiraReader = JiraData()
    projects = jiraReader.getAllTPR()
    stories = jiraReader.getAllStory()
    for project in projects:
        relatedStories = {}
        taskRelated = project.fields.issuelinks
        if len(taskRelated) > 0:
            #relatedHouse里存放当前TPR的所有关联issue
            relatedHouse = []
            for relate in taskRelated:
                relatedHouse.append(str(relate.id))
            for story in stories:
                if len(story.fields.issuelinks) > 0:
                    if str(story.fields.issuelinks[0].id) in relatedHouse:
                        subtasks = []
                        if len(story.fields.subtasks) > 0:
                            for i in range (len(story.fields.subtasks)):
                                subtasks.append(story.fields.subtasks[i].key)
                        relatedStories.setdefault(story.key, subtasks)
                else:
                    print("未关联项目的Story:", story.key)
        TPRMap.setdefault(project.key, relatedStories)
    return TPRMap




# print(getTimeRange(0))
# print(getTimeRange(1))
# print(getTimeRange(2))
printCal("anxiaole",1)
# print(getTPRMap())
# searchTPRTMMMap("TMM-706")